import multer from "multer";
import path from "path";
/**
 * 文件存储配置对象
 */
const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    const type = file.mimetype.split('/')[0]
    callback(null, `./src/uploads/${type}/${file.fieldname}`)
  },
  filename: (req, file, callback) => {
    const ext = path.extname(file.originalname)
    const fileName = file.fieldname + '-' + Date.now() + ext
    callback(null, fileName)
  }
})

/**
 * 文件上传配置对象
 */
export const upload = multer({
  storage,
  fileFilter: (req, file, callback) => {
    const allowedTypes = [
      "image/jpeg",
      "image/png",
      "image/jpg",
      "image/gif",
      "audio/mpeg",
      'audio/wav',
      'audio/mp3',
      "video/mp4",
      "application/pdf",
    ];
    if (allowedTypes.includes(file.mimetype)) {
      callback(null, true)
    } else {
      callback(new Error("Invalid file type"))
    }
  }
})